package com.wipz.eoa.iphone.officedocument;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.toft.core2.ToftException;
import com.toft.utils.UUIDHexGenerator;
import com.toft.widgets.workflow.model.CompleteTaskResult;
import com.toft.widgets.workflow.utils.ConstantUtil;
import com.wipz.eoa.iphone.BaseAction;
import com.wipz.eoa.iphone.businessProcess.AgencyCoreService;
import com.wipz.eoa.iphone.businessProcess.TaskTransitionService;
import com.wipz.eoa.iphone.businessProcess.WorkFlowCoreService;
import com.wipz.eoa.iphone.util.Constants;
import com.wipz.eoa.iphone.util.DateUtil;

/**
 * 收文管理控制类
 * @author 张涛
 * @date 2012-2-10
 */

public class ReceiveDocumentAction extends BaseAction {
	
	private static final long serialVersionUID = 1L;
	private IReceiveDocumentService receiveDocumentService;
	private Map view;
	private List list;
	private List allList;
	private AgencyCoreService agencyCoreService;
	private TaskTransitionService taskTransitionService;
	private Map bxSubmit;
	private Map insert;
	private WorkFlowCoreService workFlowCoreService;
	private Map uploadfilelist;
	public Map getUploadfilelist() {
		return uploadfilelist;
	}
	
	public void setUploadfilelist(Map uploadfilelist) {
		this.uploadfilelist = uploadfilelist;
	}
	
	public WorkFlowCoreService getWorkFlowCoreService() {
		return workFlowCoreService;
	}


	public void setWorkFlowCoreService(WorkFlowCoreService workFlowCoreService) {
		this.workFlowCoreService = workFlowCoreService;
	}


	public Map getInsert() {
		return insert;
	}


	public void setInsert(Map insert) {
		this.insert = insert;
	}


	public Map getBxSubmit() {
		return bxSubmit;
	}

	public void setBxSubmit(Map bxSubmit) {
		this.bxSubmit = bxSubmit;
	}


	public void setTaskTransitionService(TaskTransitionService taskTransitionService) {
		this.taskTransitionService = taskTransitionService;
	}


	public void setAgencyCoreService(AgencyCoreService agencyCoreService) {
		this.agencyCoreService = agencyCoreService;
	}


	public Map getView() {
		return view;
	}


	public void setView(Map view) {
		this.view = view;
	}


	public List getList() {
		return list;
	}


	public void setList(List list) {
		this.list = list;
	}


	public List getAllList() {
		return allList;
	}


	public void setAllList(List allList) {
		this.allList = allList;
	}


	public void setReceiveDocumentService(
			IReceiveDocumentService receiveDocumentService) {
		this.receiveDocumentService = receiveDocumentService;
	}


	/**
	 * 查询所有（收文管理）
	 * author：张涛
	 * date：2012-2-10
	 * time：下午03:04:15
	 * return：String
	 */
	@SuppressWarnings("unchecked")
	public String list(){
		String commiterCode = this.getRequest().getParameter("COMMITERCODE");
		if(!"".equals(commiterCode) && commiterCode != null){
			Map params = new HashMap();
			params.put("COMMITERCODE", commiterCode);
			params.put("sort", this.getRequest().getParameter("sort"));
			params.put("order", this.getRequest().getParameter("order"));
			list = receiveDocumentService.query(params);
		}
		return SUCCESS;
	}
	
	/**
	 * 查询所有（收文清单）
	 * author：张涛
	 * date：2012-2-10
	 * time：下午03:04:15
	 * return：String
	 */
	@SuppressWarnings("unchecked")
	public String allList(){
		Map params = new HashMap();
		params.put("sort", this.getRequest().getParameter("sort"));
		params.put("order", this.getRequest().getParameter("order"));
		allList = receiveDocumentService.queryAll(params);
		return SUCCESS;
	}
	
	/**
	 * 查看详细信息
	 * author：张涛
	 * date：2012-2-10
	 * time：下午05:08:10
	 * return：String
	 */
	@SuppressWarnings("unchecked")
	public String view(){
		Map params = new HashMap();
		String COMMITERCODE = this.getRequest().getParameter("COMMITERCODE");
		String taskId = this.getRequest().getParameter("taskId");
		String id = this.getRequest().getParameter("id");
		params.put("ID",id);
		view = (Map)receiveDocumentService.queryOne("receivedocument.queryById", params);
		view.put("uploadfilelist", receiveDocumentService.queryList("uploadlist", params));
		Map newMap = (Map) receiveDocumentService.queryOne("businessProcess.queryByCode",view);
		String processId = newMap == null ? "":(String)newMap.get("PROCESSID") ;
		view.put("processInstanceId", processId);
		
		if ("2".equals(view.get("PROCESS_STATUS"))
				|| "1".equals(view.get("PROCESS_STATUS"))) {
			// 公文紧急程度 1：普通 2：紧急
			if ("1".equals(view.get("EMERGENCY"))) {
				view.put("EMERGENCY", "普通");
			} else {
				view.put("EMERGENCY", "紧急");
			}
			// 公文密级 1：秘密 2：机密
			if ("1".equals(view.get("SECRET"))) {
				view.put("SECRET", "秘密");
			} else {
				view.put("SECRET", "机密");
			}
		}
		List images = receiveDocumentService.queryList("upload.queryByFormId", view);
		StringBuffer strBuf = new StringBuffer();
		for (int i = 0; i < images.size(); i++) {
			Object obj = images.get(i);
			Map image = (Map) obj;
			String fileName = (String) image.get("FILENAME");
			String realName = (String) image.get("REALNAME");
			String appandage = "<a rel='example_group' titl='公文标题' href='"
					+ this.getRequest().getContextPath()
					+ "/upload/" + fileName + "'>" + realName
					+ "</a>&nbsp;&nbsp;";
			strBuf.append(appandage);
		}
		view.put("APPENDAGE", strBuf.toString());
		
		if(null == COMMITERCODE || COMMITERCODE.isEmpty()) {
			return SUCCESS;
		}
		String userId = (String) receiveDocumentService.queryOne("user.queryId",COMMITERCODE);
		view = agencyCoreService.agencyList(Constants.RECEIVEDOCUMENT_BUSINESS_ID, userId,view);
		
		
		if(null == taskId || taskId.isEmpty()) {
			return SUCCESS;
		}
		
		view.put("taskId", taskId);
		List list =(taskTransitionService.getTaskTransition(taskId));
		Map url = new HashMap();
		StringBuffer bf = new StringBuffer();
		bf.append("/document/receiveDocument_bxSubmit.action?id=");
		bf.append(id);
		bf.append("&COMMITERCODE=");
		bf.append(COMMITERCODE);
		bf.append("&taskId=");
		bf.append(taskId);
		url.put("url", bf.toString());
		list.add(url);
		view.put("button", list);
		return SUCCESS;
		
	}
	
	public String insert(){
		Map map = new HashMap();
		String uuid = UUIDHexGenerator.getInstance().generate();
		map.put("ID", uuid);
		String billcode = Constants.getBillCode(Constants.RECEIVEDOCUMENT);
		map.put("BILLCODE", billcode); // 生成单据CODE
		map.put("PROCESS_STATUS", 0);
		map.put("APPLYDATE", DateUtil.currDateTime());
		
		String title = this.getRequest().getParameter("TITLE");
		String  commiter = this.getRequest().getParameter("COMMITER");
		String  COMMITERCODE = (String) this.getSession().get(Constants.USERINFO_USERCODE);
		String  department = this.getRequest().getParameter("DEPARTMENT");
		String  describe = this.getRequest().getParameter("DESCRIBE");
		String  doctype = this.getRequest().getParameter("DOCTYPENAME");
		String  todepartment = this.getRequest().getParameter("TODEPARTMENT");
		String  emergency = this.getRequest().getParameter("EMERGENCY");
		String  secret = this.getRequest().getParameter("SECRET");
		String agencyId = this.getRequest().getParameter("AGENCYID");
		String responsible = this.getRequest().getParameter("RESPONSIBLE");
		String content = this.getRequest().getParameter("CONTENT");
		
		map.put("TITLE", title);
		map.put("COMMITER",commiter );
		map.put("COMMITERCODE", COMMITERCODE);
		map.put("DEPARTMENT", department);
		map.put("DESCRIBE", describe);
		map.put("DOCTYPE", doctype);
		map.put("TODEPARTMENT", todepartment);
		map.put("EMERGENCY", emergency);
		map.put("SECRET", secret);
		map.put("RESPONSIBLE", responsible);
		map.put("CONTENT", content);
		
	int i = receiveDocumentService.insert("receivedocument.insert", map);
		
		if(i == 1) {
		Map variables = new HashMap();
		variables.put(ConstantUtil.BUSINESS_RECORE_ID, uuid);// 单据ID
		variables.put(ConstantUtil.BUSINESS_SN, billcode);// 单据编号
		variables.put("role", "0");
		variables.put("docType", doctype);
		// 摘要内容
		StringBuffer ct = new StringBuffer("");
		// 公文类型
		if (!doctype.isEmpty()) {
			ct.append("[").append(doctype).append("]");
		}
		// 公文标题
		if (!title.isEmpty()) {
			ct.append(title);
		}
		variables.put(ConstantUtil.BUSINESS_MONEY, content.toString());
		CompleteTaskResult result = null;
		
		Map usermap = (Map) receiveDocumentService.queryOne("user.queryUserList", COMMITERCODE);
		String userid = (String) usermap.get("ID");
		
		//查询 职责ID
		Map params = new HashMap();
		params.put("USERID",userid);
		params.put("AGENCYID", agencyId);
		Map r = new HashMap();									
		r = (Map) receiveDocumentService.queryOne("agency.queryDutyIDByUserIDAgencyID", params);
		String dutyId = (String) r.get("DUTYID");
		variables.put("dutyId", dutyId);
		variables.put("agencyId", agencyId);
		variables.put("userCode", COMMITERCODE);
		
		String businessType = Constants.RECEIVEDOCUMENT_BUSINESS_ID;
		
		try {
			result = workFlowCoreService.submitProcess(agencyId, businessType, variables,
					COMMITERCODE);
		} catch (ToftException e) {
			e.printStackTrace();
		}
			// 获取流程ID保存到流程业务维护表
			Map processMap = new HashMap();
			processMap.put("BILLID", billcode);
			processMap.put("PROCESSID", result.getProcessInstanceId());
			processMap.put("BUSINESSTYPE", businessType);
			receiveDocumentService.insert("businessProcess.insert", processMap);
			
		map.put("ID", uuid);
		map.put("PROCESS_STATUS", "1");
		
		receiveDocumentService.update("receivedocument.changeprocessstatus", map);
		map.put("nextOperators", result.getNextOperators());
		
		receiveDocumentService.update("receivedocument.getnext", map);
		
		insert = new HashMap();
		insert.put("success", true);
		insert.put("NEXTOPERATOR",result.getNextOperators());
		}
		return SUCCESS;
	}
	
	
	
	/**
	 * 收文管理审批
	 * @return
	 * 2012-2-21 下午03:10:29
	 */
	public String bxSubmit() {
		//获取ID
		String id = this.getRequest().getParameter("id");
		//用户代号
		String COMMITERCODE = this.getRequest().getParameter("COMMITERCODE");
		if(id.isEmpty() || COMMITERCODE.isEmpty()) {
			return SUCCESS;
		}
		//任务唯一标识taskId
		String taskId =  this.getRequest().getParameter("taskId");
		//处理意见
		String commentContent =  this.getRequest().getParameter("comment");
		try {
			String s = new String(commentContent.getBytes("iso-8859-1"),"utf-8");
			commentContent = java.net.URLDecoder.decode(s, "utf-8");
		} catch (UnsupportedEncodingException e) {
			return SUCCESS;
		}

		//流向
		String transition = this.getRequest().getParameter("name");
		//处理类型
		String typeaccept = this.getRequest().getParameter("pass");
		Map param = new HashMap();
		param.put("id", id);
		param.put("COMMITERCODE", COMMITERCODE);
		param.put("taskId",taskId );
		param.put("comment",commentContent );
		param.put("transition", transition);
		param.put("pass", typeaccept);
		Map mapUuid = (Map) receiveDocumentService.queryOne("user.queryAll", COMMITERCODE);
		param.put("uuitId",mapUuid.get("ORGID"));
		bxSubmit = receiveDocumentService.bxSubmit(param);
		return SUCCESS;
	}
	
	public String sent() {
		String commitercode = this.getRequest().getParameter("COMMITERCODE");
		String usercode = (String) this.getSession().get(Constants.USERINFO_USERCODE);
		if(null == usercode || "".equals(usercode)) {
		this.getSession().put(Constants.USERINFO_USERCODE, commitercode);
		}
		return SUCCESS;
	}
	
	public String getUploadfileListByID(String billcode){
		uploadfilelist=new HashMap();
		Map param=new HashMap();
		param.put("BILLCODE", billcode);
		uploadfilelist.put("uploadfilelist", param);
		return SUCCESS;
	}
}
